package com.java.util;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.java.bean.Detail;
import com.java.bean.Joke;

public class JsonParsing {

	public JsonParsing() {
		String url = "http://api.1-blog.com/biz/bizserver/xiaohua/list.do";
		String result = getJson(url);
		//System.out.println(result);
		Joke joke = toObject(result);
		Log.i("json", joke.toString());
	}

	public static String getJson(String url) {// 用这个删除
		HttpPost hPost = new HttpPost(url);
		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse httpResponse;
		try {
			httpResponse = httpclient.execute(hPost);
			Log.i("code", httpResponse.getEntity().getContentType().toString());
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(httpResponse.getEntity());
				result = new String(result.getBytes(), "utf-8");
				//Log.i("json", result);
				return result;

			} else {
				Log.i("else", "" + httpResponse.getStatusLine().getStatusCode());
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public Joke toObject(String json) {
		try {
			Joke joke = new Joke();
			JSONObject j = new JSONObject(json);
			//Log.i("json", j.getString("status"));
			joke.setStatus(j.getString("status"));
			//Log.i("json", j.getString("desc"));
			//joke.setDesc(j.getString("desc"));
			JSONArray array = j.getJSONArray("detail");
			Detail[] details = new Detail[array.length()];
			//Log.i("jsonid", array.getJSONObject(0).getString("author"));
			Detail d;
			for (int i = 0; i < details.length; i++) {
				d = new Detail();
				d.setId(array.getJSONObject(i).getString("id"));
				d.setXhid(array.getJSONObject(i).getString("xhid"));
				d.setAuthor(array.getJSONObject(i).getString("author"));
				d.setContent(array.getJSONObject(i).getString("content"));
				d.setPicUrl(array.getJSONObject(i).getString("picUrl"));
				d.setStatus(array.getJSONObject(i).getString("status"));
				details[i] = d;
			}
			joke.setDetail(details);
			return joke;
		} catch (JSONException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return null;

	}

}
